package com.prim.jmm;

/**
 * 演示可见性带来的问题
 */
public class FieldVisibility {
    int a = 1;
    /**
     * volatile 可以保证在b之前的所有操作，都是保证可见的 充当触发器的作用
     */
    volatile int b = 2;

    int abc = 1;
    int abcd = 1;

    private void change() {
        abc = 7;
        abcd = 70;
        a = 3;
        b = 0;
    }

    private void print() {
        if (b == 0) {
            //当b = 0当时候，可以确保b之前的所有操作都是可见的
            System.out.println("b=" + b + " a=" + a);
        }
        //b=3 a=3
        //b=2 a=1
        //b=2 a=3
        //可见性问题
        //b=3 a=1
    }

    public static void main(String[] args) {
        while (true) {
            FieldVisibility fieldVisibility = new FieldVisibility();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    fieldVisibility.change();
                }
            }).start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    fieldVisibility.print();
                }
            }).start();
        }
    }


}
